package chapter01.part13;

import chapter01.part2.CreateStream;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.OptionalDouble;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 各种基本类型的流 主要是为了避免自动装箱
 * 返回的是与之对应的基本类型 Optional
 * 
 * 创建:
 * IntStream.of & Arrays.stream
 * generate & iterate
 * range & rangedClosed
 * codePoints & chars
 * mapToxxx
 * 
 * 基本的静态方法:
 * sum average max min summaryStatics
 * boxed toArray
 *
 * @author insight
 * @since 2021/7/23
 */
public class PrimitiveTypeStream {
    private static final int SIZE = 10;
    
    public static void main(String[] args) {
        IntStream intStream = IntStream.of(1, 2, 3, 4, 6);
        printHead("of", intStream);
        
        int[] arr = {1, 2, 3, 4, 6, 8};
        IntStream stream = Arrays.stream(arr);
        printHead("Arrays.stream", stream);
        
        IntStream is1 = IntStream.generate(() -> (int) (Math.random() * 100)).limit(SIZE);
        printHead("Generate", is1);

        // excluded
        IntStream is2 = IntStream.range(5, 15);
        printHead("Range", is2);

        // included
        IntStream is3 = IntStream.rangeClosed(5, 15);
        printHead("RangeClosed", is3);

        Stream<String> words = CreateStream.getWordsStream().get();
        IntStream mapToInt = words.mapToInt(String::length);
        printHead("MapToInt", mapToInt);

        String s = "\uD835\uDD46 is the set of octonions";
        System.out.println(s);
        IntStream codePoints = s.codePoints();
        System.out.println(codePoints.mapToObj(c ->
                String.format("%X ", c)
        ).collect(Collectors.joining()));

        Stream<Integer> boxed = IntStream.range(0, 10).boxed();
        IntStream boxedToInt = boxed.mapToInt(Integer::intValue);
        printHead("BoxedToInt", boxedToInt);

        OptionalDouble average = IntStream.range(5, 15).average();
        // System.out.println(average.getAsDouble());
        System.out.println(average.orElse(0));

        // 数据统计
        IntSummaryStatistics intSummaryStatistics = IntStream.range(5, 15)
                .summaryStatistics();
        System.out.println(intSummaryStatistics.getMax());
    }
    
    public static void printHead(String s, IntStream intStream) {
        int[] ints = intStream.toArray();
        System.out.print(s + ": ");

        for (int i : ints) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}